import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { ChatMessage, ChatSession, ChatConfig, ChatError } from '../../../types/chat'
import { useSessionManager } from '../composables/useSessionManager'
import { aiService } from '../../shared/services/ai-service'

export const useChatStore = defineStore('chat', () => {
  // 状态定义
  const currentSessionId = ref<string | null>(null)
  const messages = ref<ChatMessage[]>([])
  const sessions = ref<ChatSession[]>([])
  const isLoading = ref(false)
  const isStreaming = ref(false)
  const error = ref<ChatError | null>(null)
  
  // 提示词模板状态
  const promptTemplates = ref<any[]>([])
  const selectedTemplateId = ref<number | null>(null)
  const isPromptActive = ref(false)
  
  // 默认配置
  const defaultConfig: ChatConfig = {
    defaultModel: '1',
    temperature: 0.7,
    maxTokens: 2000,
    topP: 0.9,
    enableMemory: false,
    enableStreaming: true,
    enableTools: false,
    supportedModels: []
  }
  
  const config = ref<ChatConfig>({ ...defaultConfig })
  
  // 计算属性
  const currentSessionMessages = computed(() => {
    if (!currentSessionId.value) return []
    return messages.value.filter(msg => msg.sessionId === currentSessionId.value)
  })
  
  const currentSession = computed(() => {
    if (!currentSessionId.value) return null
    return sessions.value.find(session => session.id === currentSessionId.value) || null
  })
  
  const hasError = computed(() => error.value !== null)
  
  // 统计信息
  const statistics = computed(() => ({
    totalMessages: messages.value.length,
    totalSessions: sessions.value.length,
    todayMessages: 0, // 可以根据需要实现
    averageResponseTime: 0, // 可以根据需要实现
    successRate: 0 // 可以根据需要实现
  }))
  
  // Actions
  function setCurrentSessionId(sessionId: string | null) {
    currentSessionId.value = sessionId
  }
  
  function setMessages(newMessages: ChatMessage[]) {
    messages.value = newMessages
  }
  
  function addMessage(message: ChatMessage) {
    messages.value.push(message)
  }
  
  function updateMessage(messageId: string, updates: Partial<ChatMessage>) {
    const index = messages.value.findIndex(msg => msg.id === messageId)
    if (index !== -1) {
      messages.value[index] = { ...messages.value[index], ...updates }
    }
  }
  
  function removeMessage(messageId: string) {
    const index = messages.value.findIndex(msg => msg.id === messageId)
    if (index !== -1) {
      messages.value.splice(index, 1)
    }
  }
  
  function clearMessages(sessionId?: string) {
    if (sessionId) {
      messages.value = messages.value.filter(msg => msg.sessionId !== sessionId)
    } else {
      messages.value = []
    }
  }
  
  function setSessions(newSessions: ChatSession[]) {
    sessions.value = newSessions
  }
  
  function addSession(session: ChatSession) {
    sessions.value.push(session)
  }
  
  function updateSession(sessionId: string, updates: Partial<ChatSession>) {
    const index = sessions.value.findIndex(session => session.id === sessionId)
    if (index !== -1) {
      sessions.value[index] = { ...sessions.value[index], ...updates }
    }
  }
  
  function removeSession(sessionId: string) {
    const index = sessions.value.findIndex(session => session.id === sessionId)
    if (index !== -1) {
      sessions.value.splice(index, 1)
    }
    
    // 如果删除的是当前会话，清空当前会话ID
    if (currentSessionId.value === sessionId) {
      currentSessionId.value = null
    }
    
    // 同时删除该会话的所有消息
    clearMessages(sessionId)
  }
  
  function setLoading(loading: boolean) {
    isLoading.value = loading
  }
  
  function setStreaming(streaming: boolean) {
    isStreaming.value = streaming
  }
  
  function setError(err: ChatError | null) {
    error.value = err
  }
  
  function clearError() {
    error.value = null
  }
  
  function updateConfig(newConfig: Partial<ChatConfig>) {
    config.value = { ...config.value, ...newConfig }
  }
  
  function resetConfig() {
    config.value = { ...defaultConfig }
  }
  
  // 提示词模板相关Actions
  function setPromptTemplates(templates: any[]) {
    promptTemplates.value = templates
  }
  
  function setSelectedTemplateId(templateId: number | null) {
    selectedTemplateId.value = templateId
  }
  
  function setIsPromptActive(active: boolean) {
    isPromptActive.value = active
  }
  
  function getSelectedTemplate() {
    if (!selectedTemplateId.value) return null
    return promptTemplates.value.find(template => template.id === selectedTemplateId.value) || null
  }
  
  // 创建新会话
async function createNewSession(userId?: number, title?: string) {
  try {
    setLoading(true)
    clearError()
    
    // 获取会话管理器
    const sessionManager = useSessionManager()
    const sessionId = sessionManager.generateSessionId(userId || 0)
    
    // 设置会话标题，如果没有提供则使用"新会话"
    const sessionTitle = title || "新会话"
    
    // 调用API创建会话
    const response = await aiService.createSession({
      sessionId,
      title: sessionTitle,
      userId: userId || 0
    })
    
    if (response.code === 0) {
      const newSession: ChatSession = {
        id: sessionId,
        title: sessionTitle,
        createdAt: Date.now(),
        lastActiveAt: Date.now(),
        messageCount: 0,
        userId: userId || 0
      }
      
      addSession(newSession)
      setCurrentSessionId(newSession.id)
        
        // 清空当前会话的消息，确保显示欢迎语句
      clearMessages(sessionId)
      
      return newSession
    } else {
      throw new Error(response.msg || '创建会话失败')
    }
  } catch (err: any) {
    setError({
      code: 'CREATE_SESSION_ERROR',
      message: err.message || '创建会话失败',
      details: err,
      retryable: true
    })
    throw err
  } finally {
    setLoading(false)
  }
}
  
  // 切换会话
  async function switchSession(sessionId: string) {
    // 先设置当前会话ID
    setCurrentSessionId(sessionId)
    
    // 检查会话是否存在，如果不存在则添加到会话列表
    if (!sessions.value.find(s => s.id === sessionId)) {
      // 如果会话不存在，添加一个新会话
      const newSession: ChatSession = {
        id: sessionId,
        title: '未命名会话',
        createdAt: Date.now(),
        lastActiveAt: Date.now(),
        messageCount: 0
      }
      addSession(newSession)
    }
    
    // 总是加载会话消息，确保能显示最新的对话记录
    try {
      await loadSessionMessagesFromBackend(sessionId)
    } catch (error) {
      console.error('加载会话消息失败:', error);
      // 加载失败时清空当前会话消息
      clearMessages(sessionId)
    }
  }
  
  // 更新会话标题
  async function updateSessionTitle(sessionId: string, newTitle: string) {
    try {
      const response = await aiService.updateSession({
        sessionId,
        title: newTitle
      })
      
      if (response.code === 0) {
        updateSession(sessionId, { title: newTitle, lastActiveAt: Date.now() })
      } else {
        throw new Error(response.msg || '更新会话标题失败')
      }
    } catch (err: any) {
      setError({
        code: 'UPDATE_SESSION_ERROR',
        message: err.message || '更新会话标题失败',
        details: err,
        retryable: true
      })
      throw err
    }
  }
  
  // 从后端加载会话列表
  async function loadSessionsFromBackend(userId: number) {
    try {
      setLoading(true)
      clearError()
      
      const response = await aiService.getSessionHistoryList()
      
      // 检查响应状态，后端返回的code应该是0
      if (response.code === 0 && response.data) {
        // 处理两种可能的数据结构：
        // 1. response.data 是一个数组（直接的会话列表）
        // 2. response.data.sessions 是一个数组（嵌套的会话列表）
        const responseData = response.data as any
        const backendSessions = Array.isArray(responseData) 
          ? responseData 
          : (responseData.sessions || [])
        
        const formattedSessions: ChatSession[] = backendSessions.map((session: any) => ({
          id: session.sessionId,
          title: session.title || '未命名会话',
          createdAt: session.createTime,
          lastActiveAt: session.updateTime || session.createTime,
          messageCount: 0, // 后端可能不提供，需要单独计算
          userId
        }))
        
        setSessions(formattedSessions)
        return formattedSessions
      } else {
        throw new Error(response.msg || '加载会话列表失败')
      }
    } catch (err: any) {
      setError({
        code: 'LOAD_SESSIONS_ERROR',
        message: err.message || '加载会话列表失败',
        details: err,
        retryable: true
      })
      throw err
    } finally {
      setLoading(false)
    }
  }
  
  // 从后端加载会话消息
  async function loadSessionMessagesFromBackend(sessionId: string) {
    try {
      setLoading(true)
      clearError()
      
      const response = await aiService.getSessionDetail(sessionId)
      
      // 检查响应状态，后端返回的code应该是0
      if (response.code === 0 && response.data) {
        // 处理两种可能的数据结构：
        // 1. response.data 是一个数组（直接的消息列表）
        // 2. response.data.messages 是一个数组（嵌套的消息列表）
        const backendMessages = Array.isArray(response.data) 
          ? response.data 
          : (response.data.messages || [])
        
        const formattedMessages: ChatMessage[] = backendMessages.map((msg: any) => ({
          id: msg.id,
          content: msg.content || '',
          type: msg.type === 'user' ? 'user' : 'assistant',
          sender: msg.type === 'user' ? 'user' : 'AI',
          timestamp: msg.timestamp,
          sessionId,
          status: 'completed',
          model: msg.model,
          contentIndex: msg.contentIndex, // 添加contentIndex字段
          metadata: {
            modelId: msg.modelId,
            model: msg.model
          }
        }))
        
        // 更新消息列表，只保留当前会话的消息
        setMessages(formattedMessages.filter(msg => msg.sessionId === sessionId))
        
        // 更新会话的消息数量
        updateSession(sessionId, { 
          messageCount: formattedMessages.length,
          lastActiveAt: Date.now()
        })
        
        return formattedMessages
      } else {
        throw new Error(response.msg || '加载会话消息失败')
      }
    } catch (err: any) {
      setError({
        code: 'LOAD_MESSAGES_ERROR',
        message: err.message || '加载会话消息失败',
        details: err,
        retryable: true
      })
      throw err
    } finally {
      setLoading(false)
    }
  }
  
  // 删除会话
  async function deleteSessionFromBackend(sessionId: string) {
    try {
      setLoading(true)
      clearError()
      
      const response = await aiService.deleteSession(sessionId)
      
      if (response.code === 0) {
        removeSession(sessionId)
      } else {
        throw new Error(response.msg || '删除会话失败')
      }
    } catch (err: any) {
      setError({
        code: 'DELETE_SESSION_ERROR',
        message: err.message || '删除会话失败',
        details: err,
        retryable: true
      })
      throw err
    } finally {
      setLoading(false)
    }
  }
  
  // 删除会话
  async function deleteSession(sessionId: string) {
    return deleteSessionFromBackend(sessionId)
  }
  
  // 发送消息
  async function sendMessage(content: string, options: any = {}) {

    if (!currentSessionId.value) {
      // 如果没有当前会话ID，创建一个新会话
      const userIdValue = options.userId || 0
      const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0')
      const sessionId = `${userIdValue}_${randomNum}`
      
      // 设置会话标题为"新会话"
      const sessionTitle = "新会话"
      
      // 创建新会话对象
      const newSession = {
        id: sessionId,
        title: sessionTitle,
        createdAt: Date.now(),
        lastActiveAt: Date.now(),
        messageCount: 0,
        userId: userIdValue
      }
      
      // 添加到会话列表
      addSession(newSession)
      
      // 设置当前会话ID
      setCurrentSessionId(sessionId)
      
      // 清空当前会话的消息，确保显示欢迎语句
      clearMessages(sessionId)
    }
    
    const sessionId = currentSessionId.value!
    const messageId = `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
    
    // 获取当前会话的消息数量，如果为0则contentIndex为0
    const sessionMessages = messages.value.filter(msg => msg.sessionId === sessionId)
    const contentIndex = sessionMessages.length === 0 ? 0 : (options.contentIndex !== undefined ? options.contentIndex : sessionMessages.length)
    
    // 创建用户消息
    const userMessage: ChatMessage = {
      id: messageId,
      content,
      type: 'user',
      sender: 'user',
      timestamp: Date.now(),
      sessionId,
      status: 'completed',
      contentIndex 
    }
    
    // 添加用户消息
    addMessage(userMessage)
    
    // 更新会话信息
    updateSession(sessionId, { 
      messageCount: currentSessionMessages.value.length,
      lastActiveAt: Date.now()
    })
    
    // 创建AI消息占位符
    const aiMessageId = `ai-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
    const aiMessage: ChatMessage = {
      id: aiMessageId,
      content: '',
      type: 'assistant',
      sender: 'AI',
      timestamp: Date.now(),
      sessionId,
      status: 'thinking',
      isStreaming: true,
      metadata: {
        modelId: options.modelId,
        model: options.model
      }
    }
    
    // 添加AI消息占位符
    addMessage(aiMessage)
    
    // 设置流式状态
    setStreaming(true)
    
    try {
      // 准备请求参数
      const requestParams = {
        userId: options.userId,
        sessionId,
        content,
        modelId: options.modelId || Number(config.value.currentModelId || config.value.defaultModel),
        temperature: options.temperature || config.value.temperature,
        maxTokens: options.maxTokens || config.value.maxTokens,
        topP: options.topP || config.value.topP,
        memory: options.memory || config.value.enableMemory,
        knowledgeId: options.knowledgeId,
        useTools: options.useTools || config.value.enableTools,
        contentIndex: options.contentIndex, // 添加contentIndex
        systemPromptId: options.systemPromptId // 添加systemPromptId参数
      }
      
      // 更新AI消息状态为streaming
      updateMessage(aiMessageId, { status: 'streaming' })
      
      // 发送流式请求
      await aiService.streamChat(requestParams, {
        onMessage: (data) => {
          if (data.event === 'message') {
            // 直接使用接收到的累积内容，不再重复累积
            updateMessage(aiMessageId, { 
              content: data.data,
              status: 'streaming'
            })
          } else if (data.event === 'thinking') {
            // 更新思考过程
            updateMessage(aiMessageId, { 
              thinking: data.data,
              status: 'thinking'
            })
          } else if (data.event === 'error') {
            // 处理错误
            updateMessage(aiMessageId, { 
              status: 'error',
              error: data.data
            })
            setError({
              code: 'STREAM_ERROR',
              message: data.data || '流式响应错误',
              retryable: true
            })
          }
        },
        onError: (err) => {
          updateMessage(aiMessageId, { 
            status: 'error',
            error: err.message
          })
          setError({
            code: 'STREAM_ERROR',
            message: err.message || '流式响应错误',
            details: err,
            retryable: true
          })
          setStreaming(false)
        },
        onComplete: () => {
          updateMessage(aiMessageId, { 
            status: 'completed',
            isStreaming: false
          })
          setStreaming(false)
          
          // 更新会话信息
          updateSession(sessionId, { 
            messageCount: currentSessionMessages.value.length,
            lastActiveAt: Date.now()
          })
        }
      })
    } catch (err: any) {
      updateMessage(aiMessageId, { 
        status: 'error',
        error: err.message
      })
      setError({
        code: 'SEND_MESSAGE_ERROR',
        message: err.message || '发送消息失败',
        details: err,
        retryable: true
      })
      setStreaming(false)
    }
  }
  
  // 重新发送消息
  async function resendMessage(messageId: string, contentIndex?: number) {
    const message = messages.value.find(msg => msg.id === messageId)
    if (!message || message.sender !== 'user') {
      setError({
        code: 'RESEND_MESSAGE_ERROR',
        message: '只能重新发送用户消息',
        retryable: false
      })
      return
    }
    
    // 使用传入的contentIndex，如果没有传入则使用消息的contentIndex
    const messageContentIndex = contentIndex !== undefined ? contentIndex : message.contentIndex
    
    // 删除原消息及其后的AI回复
    const messageIndex = messages.value.findIndex(msg => msg.id === messageId)
    if (messageIndex !== -1) {
      // 删除原消息及其后的所有消息
      const messagesToRemove = messages.value.slice(messageIndex)
      messagesToRemove.forEach(msg => removeMessage(msg.id))
    }
    
    // 重新发送消息，传递contentIndex
    await sendMessage(message.content, { contentIndex: messageContentIndex })
  }
  
  // 编辑消息
  async function editMessage(messageId: string, newContent: string) {
    const message = messages.value.find(msg => msg.id === messageId)
    if (!message || message.sender !== 'user') {
      setError({
        code: 'EDIT_MESSAGE_ERROR',
        message: '只能编辑用户消息',
        retryable: false
      })
      return
    }
    
    // 获取消息的contentIndex
    const contentIndex = message.contentIndex
    
    // 删除该消息及其后的所有消息（包括AI回复）
    const messageIndex = messages.value.findIndex(msg => msg.id === messageId)
    if (messageIndex !== -1) {
      const messagesToRemove = messages.value.slice(messageIndex)
      messagesToRemove.forEach(msg => removeMessage(msg.id))
    }
    
    // 重新发送消息，传递contentIndex
    await sendMessage(newContent, { contentIndex })
  }
  
  // 停止流式传输
  function stopStreaming() {
    // 这里可以添加停止流式传输的逻辑
    setStreaming(false)
    
    // 更新当前正在流式传输的消息状态
    const streamingMessage = messages.value.find(msg => msg.isStreaming)
    if (streamingMessage) {
      updateMessage(streamingMessage.id, { 
        status: 'completed',
        isStreaming: false
      })
    }
  }
  
  // 清空当前会话的消息
  async function clearCurrentSession() {
    if (!currentSessionId.value) {
      console.warn('没有当前会话，无法清空消息');
      return
    }

    try {
      setLoading(true)
      clearError()
      
      // 调用后端API清空会话历史
      const response = await aiService.clearSessionHistoryFromBackend(currentSessionId.value)
      
      if (response.code === 0) {
        // 清空本地消息
        clearMessages(currentSessionId.value)
        
        // 更新会话的消息数量
        updateSession(currentSessionId.value, { 
          messageCount: 0,
          lastActiveAt: Date.now()
        })
      } else {
        throw new Error(response.msg || '清空会话失败')
      }
    } catch (err: any) {
      setError({
        code: 'CLEAR_SESSION_ERROR',
        message: err.message || '清空会话失败',
        details: err,
        retryable: true
      })
      throw err
    } finally {
      setLoading(false)
    }
  }

  // 清空当前会话的所有消息（本地操作，不调用后端）
  function clearCurrentMessages() {
    if (currentSessionId.value) {
      clearMessages(currentSessionId.value)
      
      // 更新会话的消息数量
      updateSession(currentSessionId.value, { 
        messageCount: 0,
        lastActiveAt: Date.now()
      })
    }
  }

  // 重试上次失败的消息
  async function retryLastMessage() {
    // 获取最后一条用户消息
    const lastUserMessage = [...messages.value]
      .reverse()
      .find(msg => msg.sender === 'user' && msg.status !== 'completed')
    
    if (!lastUserMessage) {
      setError({
        code: 'RETRY_MESSAGE_ERROR',
        message: '没有找到可重试的消息',
        retryable: false
      })
      return
    }
    
    // 重新发送消息
    await resendMessage(lastUserMessage.id)
  }
  
  // 初始化聊天状态
async function initialize(userId: number) {
  try {
    setLoading(true)
    clearError()
    
    // 获取会话管理器
    const sessionManager = useSessionManager()
    await sessionManager.initializeSessions({ loadFromRoute: false, userId })
    
  } catch (err: any) {
    setError({
      code: 'INITIALIZE_ERROR',
      message: err.message || '初始化聊天状态失败',
      details: err,
      retryable: true
    })
  } finally {
    setLoading(false)
  }
}
  
  return {
    // 状态
    currentSessionId,
    messages,
    sessions,
    isLoading,
    isStreaming,
    error,
    config,
    
    // 提示词模板状态
    promptTemplates,
    selectedTemplateId,
    isPromptActive,
    
    // 计算属性
    currentSessionMessages,
    currentSession,
    hasError,
    statistics,
    
    // Actions
    setCurrentSessionId,
    setMessages,
    addMessage,
    updateMessage,
    removeMessage,
    clearMessages,
    setSessions,
    addSession,
    updateSession,
    removeSession,
    setLoading,
    setStreaming,
    setError,
    clearError,
    updateConfig,
    resetConfig,
    
    // 提示词模板Actions
    setPromptTemplates,
    setSelectedTemplateId,
    setIsPromptActive,
    getSelectedTemplate,
    
    // 复杂操作
    createNewSession,
    switchSession,
    updateSessionTitle,
    loadSessionsFromBackend,
    loadSessionMessagesFromBackend,
    deleteSessionFromBackend,
    deleteSession,
    sendMessage,
    resendMessage,
    editMessage,
    stopStreaming,
    clearCurrentSession,
    clearCurrentMessages,
    retryLastMessage,
    initialize
  }
}, {
  persist: {
    key: 'chat-store',
    storage: localStorage,
    pick: ['currentSessionId', 'sessions', 'config', 'selectedTemplateId', 'isPromptActive']
  }
})